package eft.android.view;

import java.util.ArrayList;
import java.util.List;

import me.croute.calendarexample.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import eft.android.controller.Controller;
import eft.android.controller.Workout;


public class DayView extends Activity implements OnClickListener{

	private Controller controller;
	ArrayList<String> exerciseList = new ArrayList<String>();
	ArrayAdapter<String> adapter = null;
	List<Workout> workoutList;

	private TableLayout dayExercises;

	private double dayWeight;

	private int day;
	private int month;
	private int year;

	Button addWorkout; 
	Button addWeight;


	/* Need a way of accessing the workouts done during a specific day from the controller.
	 * Don't see any method in controller.java that'll let me do that.
	 * Also need a method for accessing the weight from a day.
	 */
	public void onCreate (Bundle savedInstanceState) {
		try 
		{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.dayview);

			addWorkout = (Button) findViewById(R.id.dayViewAddWorkout);
			addWeight = (Button) findViewById(R.id.dayViewAddWeight);

			addWorkout.setOnClickListener( this );
			addWeight.setOnClickListener( this );

			Bundle extras = getIntent().getExtras();

			dayExercises = (TableLayout) findViewById(R.id.dayExercises);

			if (extras != null)
			{
				month = extras.getInt( this.getPackageName() + ".month");
				year  = extras.getInt( this.getPackageName() + ".year");
				day   = extras.getInt( this.getPackageName() + ".day" );
			}

			controller = Controller.getInstance();

			dayWeight = controller.getWeightByDay(day, month, year );

			if ( dayWeight != 0.0 ){
				setWeightButtonText( ((Double) dayWeight).toString() );
			}

			TextView dateTV = (TextView) findViewById(R.id.date);
			dateTV.setText( getMonth(month) + " " + day);
			/*
			ListView exercisesList = (ListView) findViewById(R.id.dayExercises);
			adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, exerciseList);
			exercisesList.setAdapter(adapter); 
			exercisesList.setTextFilterEnabled(true);
			 */
			fillExerciseTable();

		}
		catch (Exception e) {
			Log.e("ERROR", "ERROR IN CODE: " + e.toString());
			e.printStackTrace();
		}
	}

	public void onClick(View v)
	{
		switch(v.getId())
		{
		case R.id.dayViewAddWorkout:
			Intent addNewWorkout = new Intent(getApplicationContext(), AddWorkout.class);

			long date = Controller.createDateLong(day, month, year);

			addNewWorkout.putExtra( "Date", date );

			startActivity(addNewWorkout);

			break;

		case R.id.dayViewAddWeight:

			final AlertDialog.Builder builder = new AlertDialog.Builder(this);	

			builder.setTitle( getMonth(month) + " " + day);
			builder.setIcon(me.croute.calendarexample.R.drawable.eft);

			builder.setMessage("Add personal weight in pounds:");

			final EditText weightBox = new EditText(this);
			builder.setView(weightBox);

			builder.setPositiveButton("Save", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// onItemClick(parent,v,position,arg3);

					String textString = weightBox.getText().toString();
					textString = textString.trim();
					float weight = -1; 

					try{
						weight = Float.parseFloat( textString ); 
					}catch(Exception ex){}

					if ( weight > 0 && weight < 1000 ){

						/* round to one decimal place */

						String w = ( (Float) weight ).toString();

						int dot = w.indexOf( '.' );

						if( dot == -1){
							w = w + ".0";
						}
						else{
							w = w.substring(0, dot + 2);
						}

						setWeightButtonText( w );

						Context context = getApplicationContext();
						CharSequence text = "Weight Added";
						int duration = Toast.LENGTH_SHORT;

						Toast toast = Toast.makeText(context, text, duration);
						toast.show();

						controller.saveWeight( w, day, month, year);
					}
					else{

						Context context = getApplicationContext();
						CharSequence text = "Invalid weight. Please enter a valid weight.";
						int duration = Toast.LENGTH_LONG;

						Toast toast = Toast.makeText(context, text, duration);
						toast.show();
					}
				}
			});
			builder.show();

			break;
		}
	}

	private void setWeightButtonText(String w){
		addWeight.setText( "Day Weight: " + w + " lbs");
	}

	private void fillExerciseTable() {

		TableRow row;
		TextView tv;
		
		// Clear the table from previous data 
		dayExercises.removeAllViewsInLayout();
		row = new TableRow(this);
		dayExercises.addView(row, new TableLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		

		workoutList = new ArrayList<Workout>();
		long date = Controller.createDateLong(day, month, year);

		try {
			workoutList = new 
				ArrayList<Workout>(controller
					.getAllUserWorkoutsByDate(date));
			if( workoutList.size() == 0 ){
				Toast.makeText(this, "No workouts have been added for " 
					+ getMonth(month) + " " + day, Toast.LENGTH_LONG).show();
			}
		} catch (Exception e){
			Toast.makeText(this, "No workouts have been added for " 
					+ getMonth(month) + " " + day, Toast.LENGTH_LONG).show();
			dayExercises.removeAllViewsInLayout();
			return;
		}
		
		workoutList = controller.nameOrder(workoutList);

		dayExercises.removeAllViewsInLayout();

		// Fill out the exercise history table

		for (int i = 0; i < workoutList.size(); i++) {
			row = new TableRow(this);

			tv = new TextView(this);
			
    		if( workoutList.get(i).getTitle().length() > 30 ){
    			tv.setText(workoutList.get(i).getTitle().substring(0, 30) +"... " );
    		}
    		else{
    			tv.setText(workoutList.get(i).getTitle() );
    		}
    		
			tv.setTextSize(20);

			row.addView(tv);
			row.setId(i);

			dayExercises.addView(row, new TableLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

			row.setOnClickListener(new  OnClickListener() {
				
				// Row was selected
				public void onClick(View v) {
					// v.setBackgroundColor(Color.DKGRAY);

					//row.getId();
					displayWorkoutDetails(v.getId());
				}
			});
		} 
	}

	public void displayWorkoutDetails(int id){
		// TODO: Get the description, time, etc... from the selected exercise.
		final int delLocation = id;

		/** To hold workout details */
		String workoutDetails = String.format
		("%s\n\nWeight: %s\nReps: %s\nTime: %s\n\n%s", 
				workoutList.get(id).getDescription(), 
				workoutList.get(id).getWeight(), 
				workoutList.get(id).getReps(),
				( workoutList.get(id).getTime() == 0 ? "": workoutList.get(id).getTimeReadable() ),
				( workoutList.get(id).getNotes() == null ? "": workoutList.get(id).getNotes() )
				);

		// Build an exercise description window to display
		AlertDialog.Builder alertDialogBuilder = 
			new AlertDialog.Builder(this);

		alertDialogBuilder.setTitle(workoutList.get(id).getTitle());
		alertDialogBuilder.setIcon(me.croute.calendarexample.R.drawable.eft);

		alertDialogBuilder.setMessage(workoutDetails)
		.setNeutralButton("Delete Workout",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int i) {	
				controller.deleteWorkout(workoutList.get(delLocation));
				fillExerciseTable();
				dialog.cancel();
			}
		});

		alertDialogBuilder.setPositiveButton("Edit Workout",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				Workout w = workoutList.get(delLocation);
				
				Intent workoutUpdate = new Intent( getApplicationContext(), AddWorkout.class );
				
				workoutUpdate.putExtra(  "ID", w.getID());
				workoutUpdate.putExtra(  "Title", w.getTitle());
				workoutUpdate.putExtra(  "Description", w.getDescription());
				workoutUpdate.putExtra(  "Date", w.getDate());
				workoutUpdate.putExtra(  "Reps", w.getReps());	
				workoutUpdate.putExtra(  "Weight", w.getWeight());				
				workoutUpdate.putExtra(  "Time", w.getTime());	
				workoutUpdate.putExtra(  "Notes", w.getNotes());	
				
				startActivity(workoutUpdate);
				
				// fillExerciseTable();
				// dialog.cancel();
			}
		});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();

	}

	private String getMonth(int month)
	{
		String monthStr;
		switch(month)
		{
		case 1:
			monthStr = "January ";
			break;
		case 2:
			monthStr = "February ";
			break;
		case 3:
			monthStr = "March ";
			break;
		case 4:
			monthStr = "April ";
			break;
		case 5:
			monthStr = "May ";
			break;
		case 6:
			monthStr = "June ";
			break;
		case 7:
			monthStr = "July ";
			break;
		case 8:
			monthStr = "August ";
			break;
		case 9:
			monthStr = "September ";
			break;
		case 10:
			monthStr = "October ";
			break;
		case 11:
			monthStr = "November ";
			break;
		case 12:
			monthStr = "December ";
			break;
		default:
			monthStr = "Error ";
			break;
		}

		return monthStr;
	}

	private String getWeight()
	{
		//dayWeight = (controller.getWeight(date)).getWeight() ;
		//dayWeight = 160;
		return ("Weight: " + dayWeight + " lbs.");

	}

	public void onBackPressed() {        
		Intent backToCalendar = new Intent(getApplicationContext(), CalendarViewActivity.class);
		startActivity(backToCalendar);
	}
}






